import React from 'react'
import { Send, Bot, User, FileText, Zap } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import StreamingMarkdownRenderer from '@/components/StreamingMarkdownRenderer'
import { ConversationSummaryComponent } from '@/components/ConversationSummary'

interface Message {
  id: string
  content: string
  role: 'user' | 'assistant'
  timestamp: Date
  isStreaming?: boolean
}

interface ChatInterfaceProps {
  messages: Message[]
  inputMessage: string
  setInputMessage: (message: string) => void
  onSendMessage: () => void
  isLoading: boolean
  conversationId?: string
  isAgentMode?: boolean
  onToggleAgentMode?: (enabled: boolean) => void
}

export function ChatInterface({
  messages,
  inputMessage,
  setInputMessage,
  onSendMessage,
  isLoading,
  conversationId,
  isAgentMode = false,
  onToggleAgentMode
}: ChatInterfaceProps) {
  const messagesEndRef = React.useRef<HTMLDivElement>(null)
  const [showSummary, setShowSummary] = React.useState(false)

  React.useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      onSendMessage()
    }
  }

  const formatMessage = (content: string, isUser: boolean, isStreaming: boolean = false) => {
    if (isUser) {
      // 用户消息保持纯文本，避免执行恶意代码
      return content.split('\n').map((line, index) => (
        <span key={index}>
          {line}
          <br />
        </span>
      ))
    }
    // AI消息使用流式Markdown渲染
    return <StreamingMarkdownRenderer content={content} />
  }

  return (
    <div className="flex flex-col h-full bg-background">
      <Card className="flex-1 flex flex-col m-4 rounded-lg overflow-hidden">
        <CardHeader className="border-b">
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              {isAgentMode ? <Zap className="w-5 h-5 text-yellow-500" /> : <Bot className="w-5 h-5" />}
              {isAgentMode ? 'AI Agent Assistant' : 'AI Chat Assistant'}
              {isAgentMode && (
                <span className="text-xs bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full">
                  Agent Mode
                </span>
              )}
            </CardTitle>
            <div className="flex items-center gap-2">
              {onToggleAgentMode && (
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground">Agent Mode</span>
                  <Button
                    variant={isAgentMode ? "default" : "outline"}
                    size="sm"
                    onClick={() => onToggleAgentMode(!isAgentMode)}
                    className="flex items-center gap-2"
                  >
                    <Zap className="w-4 h-4" />
                    {isAgentMode ? 'ON' : 'OFF'}
                  </Button>
                </div>
              )}
              {conversationId && conversationId !== 'unknown' && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowSummary(true)}
                  className="flex items-center gap-2"
                >
                  <FileText className="w-4 h-4" />
                  View Summary
                </Button>
              )}
            </div>
          </div>
        </CardHeader>
        
        <CardContent className="flex-1 flex flex-col p-0 min-h-0">
          <div className="flex-1 overflow-y-auto p-4 space-y-4 max-h-[calc(100vh-12rem)]">
            {messages.length === 0 ? (
              <div className="flex items-center justify-center h-full text-muted-foreground">
                <div className="text-center">
                  <Bot className="w-12 h-12 mx-auto mb-4 opacity-50" />
                  <p>Start a conversation with the AI assistant</p>
                </div>
              </div>
            ) : (
              messages.map((message) => (
                <div
                  key={message.id}
                  className={`flex gap-3 ${
                    message.role === 'user' ? 'justify-end' : 'justify-start'
                  }`}
                >
                  <div
                    className={`flex items-start gap-3 max-w-[80%] ${
                      message.role === 'user' ? 'flex-row-reverse' : ''
                    }`}
                  >
                    <div
                      className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                        message.role === 'user'
                          ? 'bg-primary text-primary-foreground'
                          : 'bg-secondary text-secondary-foreground'
                      }`}
                    >
                      {message.role === 'user' ? (
                        <User className="w-4 h-4" />
                      ) : (
                        <Bot className="w-4 h-4" />
                      )}
                    </div>
                    <div
                      className={`rounded-lg px-4 py-3 ${
                        message.role === 'user'
                          ? 'bg-primary text-primary-foreground'
                          : 'bg-muted text-muted-foreground'
                      }`}
                    >
                      <div className="text-sm">
                        {formatMessage(message.content, message.role === 'user', message.isStreaming)}
                      </div>
                      <div className="text-xs opacity-70 mt-1">
                        {message.timestamp.toLocaleTimeString()}
                      </div>
                    </div>
                  </div>
                </div>
              ))
            )}
            
            {isLoading && (
              <div className="flex gap-3 justify-start">
                <div className="flex items-start gap-3 max-w-[80%]">
                  <div className="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-secondary text-secondary-foreground">
                    <Bot className="w-4 h-4" />
                  </div>
                  <div className="rounded-lg px-4 py-3 bg-muted text-muted-foreground">
                    <div className="typing-indicator">
                      <div className="typing-dot" style={{ '--delay': 0 } as React.CSSProperties} />
                      <div className="typing-dot" style={{ '--delay': 1 } as React.CSSProperties} />
                      <div className="typing-dot" style={{ '--delay': 2 } as React.CSSProperties} />
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            <div ref={messagesEndRef} />
          </div>
          
          <div className="border-t p-4 flex-shrink-0">
            <div className="flex gap-2">
              <Input
                value={inputMessage}
                onChange={(e) => setInputMessage(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder={isAgentMode ? "Ask the AI agent anything..." : "Type your message..."}
                disabled={isLoading}
                className="flex-1"
              />
              <Button
                onClick={onSendMessage}
                disabled={isLoading || !inputMessage.trim()}
                size="icon"
              >
                <Send className="w-4 h-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
      
      <ConversationSummaryComponent
        conversationId={conversationId}
        isVisible={showSummary}
        onClose={() => setShowSummary(false)}
      />
    </div>
  )
}